<template>
  <ul class="chart-legend" :class="wrapperClass">
    <li
      v-for="(leg, index) in data"
      :class="{
        active: selectMode && isSelected(leg),
        static: !selectMode
      }"
      :key="leg"
      @click="handleClick(leg)"
    >
      <span :style="{ color: colors[index], background: colors[index] }" />{{
        leg
      }}
    </li>
  </ul>
</template>
<script lang="ts">
/**
 * ${generate by}
 */
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
type LegendConfig = {
  position: 'top' | 'left' | 'right' | 'bottom'
  selectMode: false
}
@Component
export default class CustomLegend extends Vue {
  @Prop({ default: () => [] }) data?: string[]
  @Prop({ default: () => [] }) colors?: string[]
  @Prop({ default: () => {} }) config?: LegendConfig | boolean

  get wrapperClass() {
    const obj: any = {}
    if (typeof this.config === 'object') {
      const { position = 'top' } = this.config
      obj['chart-legend--' + position] = !!position
    }
    return obj
  }
  get selectMode() {
    if (typeof this.config === 'boolean') {
      return false
    }
    // @ts-ignore
    return this.config.selectMode
  }
  selected: any = {}
  isSelected(name: string) {
    return typeof this.selected[name] === 'undefined' || this.selected[name]
  }
  handleClick(name: string) {
    if (!this.selectMode) {
      return
    }
    if (typeof this.selected[name] === 'undefined') {
      this.$set(this.selected, name, false)
    } else {
      this.selected[name] = !this.selected[name]
    }
    this.$emit('change', { ...this.selected })
  }
}
</script>
<style lang="scss">
.chart-legend {
  list-style: none;
  margin: 0 -10px;
  padding: 0;
  position: absolute;
  right: 0;
  left: 0;
  text-align: right;
  z-index: 100;
  &[class$='left'],
  &[class$='right'] {
    left: 0;
    right: auto;
    top: 0;
    bottom: 0;
    margin: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    li {
      display: flex;
      margin: 5px 0;
    }
  }
  @at-root &--right {
    left: auto !important;
    right: 0 !important;
  }
  @at-root &--bottom {
    top: auto;
    bottom: 0;
  }
  li {
    display: inline-flex;
    align-items: center;
    user-select: none;
    cursor: pointer;
    margin: 0 10px;
    padding: 4px 15px 4px 15px;
    border-radius: 2px;
    transition: all 0.2s;
    &.static {
      cursor: default;
    }
    &:not(.static):hover {
      background: #f0f3f7;
      opacity: 0.8;
    }
    &.active {
      background: #f0f3f7;
      opacity: 1;
    }
    span {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin-right: 15px;
      position: relative;
      &::after {
        content: '';
        position: absolute;
        left: -10px;
        right: -10px;
        height: 2px;
        top: 4px;
        background: inherit;
      }
    }
  }
}
</style>
